﻿/*!
* jQuery post get plugin: 
* 
* version 0.1 2011-03-01
* Requires jQuery v1.4.2 or later
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Kim Seoung Min
* Company : Kongyoung DB
*/

function PostJsonData(url, pi, callback, err) {
	$.ajax({
		type: "POST",
		url: url,
		data: pi.toXml(),
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		async: true,
		success: function (msg) {
		    if (msg != null) callback(JSON_Serialized(msg.d)); 
        },
		error: function (msg) {
		    //alert("PostJsonData : URL: " + url + " MSG: " + pi.toXml() + " / " + msg.responseText); //2011-03-21 Jin Woochul. Modify for more accurate error message
		}
	});
}

function PostJsonSync(url, pi) {
    var rlt = $.ajax({
        type: "POST",
        url: url,
        data: pi.toXml(),
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).responseText;
    return JSON_Serialized(JSON_Serialized(rlt).d);
}

function PostStrSync(url, pi) {
    var rlt = $.ajax({
        type: "POST",
        url: url,
        data: pi.toXml(),
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).responseText;
    return rlt;
}

function PostJsonStr(url, pi, callback, err) {
    $.ajax({
        type: "POST",
        url: url,
        data: pi.toXml(),
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (msg) { if (msg != null) callback(JSON_Serialized(msg.d)); },
        error: function (msg) {
          //  alert(msg);
        }
    });
}


function GetJsonData(url,callback, err) {
    $.ajax({
        type: "GET",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function (msg) { if (msg != null) callback(JSON_Serialized(msg.d)); },
        error: function (msg) {
        //alert(msg); 
        }
    });
}

function GetJsonSync(url) {
    var rlt = $.ajax({
        type: "GET",
        url: url,
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "XML"
    }).responseText;       
    _obj = JSON_Serialized(rlt);
    if (typeof (_obj.d) == 'Object')
        return _obj.d;
    else
        return _obj;
}

function GetJsonStr(url, jdata) {
    var rlt = $.ajax({
        type: "GET",
        url: url,
        async: false,
        data: $.param(jdata),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).responseText;
    return JSON_Serialized(rlt).d;
}

         

            
/// Json의 문자열을 객체로 전환하기위한 코드
function JSON_Serialized(jsonString) {
    var _data;
    if (typeof (jsonString) == "object") {
        return jsonString
    }
    else {
        try {


            var _data = jsonString.replace(/[\u0000\u00ff]/g, ''); //.replace(/"/g, "'");
            _data = _data.replace(/\s+/g," ").replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,"$1");

            return eval('(' + _data + ')');
        }
        catch (e1) {
            //alert(jsonString);
           // alert("JSON_Serialized()  eval error / " + e1.message + " / " + _data);
        }
    }
}

var unescapeHtml = function(html) {
    var temp = document.createElement("div");
    temp.innerHTML = html;
    var result = temp.childNodes[0].nodeValue;
    temp.removeChild(temp.firstChild)
    return result;
} 

///  json parameters
function JSONClientParameters() {
    var _pl = new Array();
    this.add = function(name, value) {
        _pl[name] = value;
        return this;
    }
    this.toXml = function() {
        var xml = "{";
        var i = 0;
        for (var p in _pl) {
            if (i > 0) xml += ",";
            xml += p + ':"' + JSONClientParameters._serialize(_pl[p]) + '"';
            i++;
        }
        xml += "}";
        return xml; // return unescapeHtml(xml);
    }

}

JSONClientParameters._serialize = function (o) {
    var s = "";
    switch (typeof (o)) {
        case "string":

            s += o.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace("\\", "&#92;").replace(/"/g, "&#34;");
            // s = s.replace(/=(.[^&]*)/g, function ($0, $1) { return "=" + escape(decodeURIComponent($1).replace(/\n/g, "\r\n")) });
            break;
        case "number":
        case "boolean":
            s += o.toString(); break;
        case "object":
            // Date
            if (o.constructor.toString().indexOf("function Date()") > -1) {

                var year = o.getFullYear().toString();
                var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
                var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
                var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
                var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
                var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
                var milliseconds = o.getMilliseconds().toString();
                var tzminutes = Math.abs(o.getTimezoneOffset());
                var tzhours = 0;
                while (tzminutes >= 60) {
                    tzhours++;
                    tzminutes -= 60;
                }
                tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
                tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
                var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
                s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
            }
            // Array
            else if (o.constructor.toString().indexOf("function Array()") > -1) {
                for (var p in o) {
                    if (!isNaN(p))   // linear array
                    {
                        (/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
                        var type = RegExp.$1;
                        switch (type) {
                            case "":
                                type = typeof (o[p]);
                            case "String":
                                type = "string"; break;
                            case "Number":
                                type = "int"; break;
                            case "Boolean":
                                type = "bool"; break;
                            case "Date":
                                type = "DateTime"; break;
                        }
                        s += "<" + type + ">" + JSONClientParameters._serialize(o[p]) + "</" + type + ">"
                    }
                    else    // associative array
                        s += "<" + p + ">" + JSONClientParameters._serialize(o[p]) + "</" + p + ">"
                }
            }
            // Object or custom function
            else
                for (var p in o)
                    s += "<" + p + ">" + JSONClientParameters._serialize(o[p]) + "</" + p + ">";
            break;
        default:
            throw new Error(500, "JSONClientParameters: type '" + typeof (o) + "' is not supported");
    }
    return s;
}

